<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use cmf\controller\AdminBaseController;
use think\Db;
use think\Validate;
use plugins\contract\contract_template\Config;

class PublicController extends AdminBaseController
{
    public function _initialize()
    {
    }

    /**
     * 后台登陆界面
     */
    public function login()
    {
        $loginAllowed = session("__LOGIN_BY_CMF_ADMIN_PW__");
        if (empty($loginAllowed)) {
            $this->error('非法登录!', cmf_get_root() . '/');
        }

        $admin_id = session('ADMIN_ID');
        if (!empty($admin_id)) {//已经登录
            redirect(url("admin/Index/index"));
        } else {
            $site_admin_url_password = config("cmf_SITE_ADMIN_URL_PASSWORD");
            $upw                     = session("__CMF_UPW__");
            if (!empty($site_admin_url_password) && $upw != $site_admin_url_password) {
                redirect(ROOT_PATH . "/");
            } else {
                session("__SP_ADMIN_LOGIN_PAGE_SHOWED_SUCCESS__", true);
                $result = hook_one('admin_login');
                if (!empty($result)) {
                    return $result;
                }
                return $this->fetch(":login");
            }
        }
    }

    /**
     * 登录验证
     */
    public function doLogin()
    {
        $loginAllowed = session("__LOGIN_BY_CMF_ADMIN_PW__");
        if (empty($loginAllowed)) {
            $this->error('非法登录!', cmf_get_root() . '/');
        }

		
        $captcha = $this->request->param('captcha');
        if (empty($captcha)) {
            $this->error(lang('CAPTCHA_REQUIRED'));
        }
        //验证码
        if (!cmf_captcha_check($captcha)) {
            $this->error(lang('CAPTCHA_NOT_RIGHT'));
        }

        $name = $this->request->param("username");
        if (empty($name)) {
            $this->error(lang('USERNAME_OR_EMAIL_EMPTY'));
        }
        $pass = $this->request->param("password");
        if (empty($pass)) {
            $this->error(lang('PASSWORD_REQUIRED'));
        }
        if (strpos($name, "@") > 0) {//邮箱登陆
            $where['user_email'] = $name;
        } else {
            $where['user_login'] = $name;
        }

        $result = Db::name('user')->where($where)->find();

        if (!empty($result) && $result['user_type'] == 1) {
            if (cmf_compare_password($pass, $result['user_pass'])) {
                $groups = Db::name('user_attach')
                    ->alias("a")
                    ->join('role b', 'a.role_id =b.id')
                    ->where(["a.user_id" => $result["id"], "status" => 1])
                    ->find();
                if($groups['company_id']!=8){
                    $this->error('用户账户不存在，请检查！');
                }
                if ($result["id"] != 1 && (empty($groups['role_id']) || empty($result['user_status']))) {
                   // $this->error(lang('USE_DISABLED'));
                   $this->error('账户已被停用！');
                }
                if($result['user_status']==3){
                    $this->error('申请账号未被通过！');
                }
                if($result['user_status']==2){
                    $this->error('申请账号正在审核中，请等待！');
                }
                //登入成功页面跳转
                session('ADMIN_ID', $result["id"]);
                session('name', $result["user_login"]);
                $result['last_login_ip']   = get_client_ip(0, true);
                $result['last_login_time'] = time();
                $token                     = cmf_generate_user_token($result["id"], 'web');
                if (!empty($token)) {
                    session('token', $token);
                }
                Db::name('user')->update($result);
                cookie("admin_username", $name, 3600 * 24 * 30);
                session("__LOGIN_BY_CMF_ADMIN_PW__", null);
                $this->success(lang('LOGIN_SUCCESS'), url("admin/Index/index").'?key=admin_enter');
            } else {
                $this->error(lang('PASSWORD_NOT_RIGHT'));
            }
        } else {
            $this->error(lang('USERNAME_NOT_EXIST'));
        }
    }

    /**
     * 后台管理员退出
     */
    public function logout()
    {
        session('ADMIN_ID', null);
        return redirect(url('/', [], false, true));
    }



    //合同预览
    public function contract_preview()
    {

        $param=$this->request->param('cpxtckiadpekskksu9k');
        $param=json_decode(base64_decode($param));
        $id=$param->id;
        $mbid=$param->mbid;
        //获取合同关联的数据
        $res=Db::view('contract')->view('lx','name,mobile','lx.id=contract.client_id')->view('kehu','company,address','lx.kh_id=kehu.id')->view('user','user_login,sign as user_sign','user.id=contract.principal_id')->where('contract.id='.$id)->find();
                //所需工时
        $res['work_time']=($res['end_date']-$res['start_date'])/86400;
        //时间格式化：
        $res['contract_date']=date("Y年m月d日",$res['contract_date']);//签约时间
        $res['lose_date']=date("Y年m月d日",($res['end_date']+$res['aftersale_date']*86400));//合同失效时间
        $res['start_date']=date("Y年m月d日",$res['start_date']);//工期开始时间
        $res['end_date']=date("Y年m月d日",$res['end_date']);//工期结束时间
        //转换大小写金额
        
        $res['contract_amount']="￥".$res['contract_amount']."元 大写：( ".cny($res['contract_amount'])." )";

        //公章
        $res['user_seal']="__STATIC__/images/seal.jpg";//乙方公章
        //获取模板数据
        $mb=Db::name('htmodel')->where('id='.$mbid)->field('content,content1')->find();
        //解码
        $content=htmlspecialchars_decode($mb['content']);
        $content1=htmlspecialchars_decode($mb['content1']);
        //替换模板中标记数据数据
        //模板填充参数处理
        $find=[];//查找的字符串
        $replace=[];//替换的字符串
        //$param=htparamConfig();
        $param=Config::get('param_config');
        $i=0;
        foreach ($res as $key=>$value) {
            
            if(array_key_exists($key,$param)){
                if($param[$key]['type']=='string'){
                    if($key=='versions'){//版本数据处理
                        $value=implode("&nbsp;&nbsp;&nbsp;&nbsp;",json_decode($value));
                    }
                    $find[$i]=$param[$key]['data'];
                    $replace[$i]=$value;
                    $i++;
                }else{
                    if($key=='detail'){//开发细则数据处理
                        $value=htmlspecialchars_decode($value);
                    }
                    $param[$key]['data']=$value;
                }
            }
        }

        //替换模板的标记字符串
        $mb=str_replace($find, $replace, $content);
        $mb1=str_replace($find, $replace, $content1);

        //echo date('Y年m月d日',time());
        //dump($mb);
        $stage_info=$param['stage_info']['data'];//json_decode($param['stage_info']['data']);//开发表格数据
        $this->assign('project_name',$res['project_name']);
        $this->assign('mb',html_entity_decode($mb));
        $this->assign('mb1',html_entity_decode($mb1));
        $this->assign('stage_info',$stage_info);
        return $this->fetch(":contract_preview");
    }

    /**
     * 管理系统公司账号申请       
     * @return [type] [description]
     */
    public function companyaccount()
    {
        $type=Db::name('company_type')->select();
        $this->assign('company_type',$type);
        return  $this->fetch(":companyaccount");
    }

    /**
     * 公司申请
     * @return [type] [description]
     */
    public function company_add()
    {
        if(!$this->request->isPost())
        {
            $this->error('请求类型错误！');
        }

        $data=$this->request->param();
        //去空
        foreach ($data as $key => $value) {
            $value=trim($value);
            $data[$key]=$value;
        }

        //  数据验证
        $rule=[
            'company_name'=>"require|max:200",
            'company_num'=>"require|max:50",
            'company_type'=>"require",
            'username'=>"require|max:20",
            'password'=>"require|max:20|min:6",
            'mobile'=>"require",
            'captcha'=>"require"
        ];
        $msg=[
            'company_name.require'=>'公司名称不能为空',
            'company_name.max'=>'公司名称不能超过200个字符',
            'company_num.require'=>'公司组织代码不能为空',
            'company_type.require'=>'请选择所属行业',
            'company_num.max'=>'公司组织代码不能超过50个字符',
            'username.require'=>'用户名称不能为空',
            'username.max'=>'用户名不能超过20个字符',
            'password.require'=>'密码不能为空',
            'password.max'=>'密码不能超过20个字符',
            'mobile.require'=>'手机号码不能为空',
            'captcha.require'=>'验证码不能为空'
        ];
        $validate =new Validate($rule,$msg);
        if(!$validate->check($data)){
            $this->error($validate->getError());
        }
        //验证手机号
        $rule = '/^0?(13|14|15|17|18|19)[0-9]{9}$/';
        $result = preg_match($rule, $data['mobile']);
        if (!$result) {
            $this->error('请填写11位正确的手机号！');
        }

        //验证码
        if (!cmf_captcha_check($data['captcha'])) {
            $this->error(lang('CAPTCHA_NOT_RIGHT'));
        }

        //启用事务
        Db::startTrans();
        try {
                //公司表加入数据  
                $company['company_name']=$data['company_name'];
                $company['company_num']=$data['company_num'];
                $company['company_type']=$data['company_type'];
                $company['address']=$data['address'];
                $company['tel']=$data['tel'];
                $company['url']=$data['url'];
                $company['parent_id']=8;
                $company['create_time']=time();
                $company['status']=2;//审核中

                $company_id=Db::name('company')->insertGetId($company);

                //创建基础部门
                //$department['department_NO']=10;
                $department['status']=1;
                $department['parent_id']=0;
                $department['name']="办公室";
                $department['remark']=$company['company_name'];
                $department['company_id']=$company_id;

                $department_id=Db::name('department')->insertGetId($department);

                //创建基础角色      
                $role['parent_id']=1;
                $role['department_id']=$department_id;
                $role['status']=1;
                $role['create_time']=time();
                $role['name']=$company['company_name']."(CEO)";
                $role['remark']=$company['company_name']." 公司帐号";
                $role['company_id']=$company_id;

                $role_id=Db::name('role')->insertGetId($role);
                
                //创建管理员
                $user['user_type']=1;
                $user['create_time']=time();
                $user['user_status']=2;//审核中
                $user['user_login']=$data['username'];
                $user['user_pass']=cmf_password($data['password']);
                $user['mobile']=$data['mobile'];
                $user_id=Db::name('user')->insertGetId($user);

                //将用户关联到 公司 部门   角色 
                $ins['user_id']=$user_id;
                $ins['company_id']=$company_id;
                $ins['department_id']=$department_id;
                $ins['role_id']=$role_id;
                Db::name('user_attach')->insert($ins);
                //提交事务
                Db::commit();
        } catch (Exception $e) {
            //回滚事务
            Db::rollback();        
            $this->error('提交失败，请稍后再试！错误：x000');    
        }
        $this->success('提交成功！',url('public/login'));
    }


    /*临时方法  查看答题*/
    public  function  shows()
    {
        $res=Db::name('answer_sheet')->select()->toArray();
        $answers=[];
        foreach ($res as $key => $value) {
            $answer=json_decode($value['answer'],true);
            $td='<td>'.(++$key).'</td>';
            $sum=0;
            for($i=1;$i<21;$i++){
                $isFind=false;
                foreach ($answer as $k => $v) {
                    if($i==$v['id']){
                        $isFind=true;
                        if($v['answer']===$v['right']){
                            $td.='<td style="color:green;">'.$v['answer'].'</td>';
                            $sum+=5;
                        }else{
                            $td.='<td style="color:red;">'.$v['answer'].'</td>';
                        }
                        break;
                    }
                }
                if(!$isFind){
                    $td.='<td style="color:#3498DB;">未答</td>';
                }
            }
            $td.='<td>'.$sum.'</td>';
            $td.='<td>'.$value['remark'].'</td>';
            $answers[]=['td'=>$td];
        }
        $this->assign('list',$answers);
        return $this->fetch(':show');
    }


}